/**
 * Created by ly on 2015/4/22.
 */
;
if(typeof jQuery === "undefined"){
  throw new Error("jQuery 类库找不到！");
};

+function($){
  "use strict";

  $.extend({
    cinit: configInit,
    sinit: signInit,
    getUrl: getSignUrl,
    signAlgorithm: signAlgorithm
  });

  /**
   * 配置信息
   * @type {{token: string, loginUrl: string, appKey: string, secretKey: string, adminSignUrl: string, adminServerUrl: string, rootUrl: string, indexUrl: string}}
   */
  var configs = {
    loginUrl: "/admin/login.html",
    //appKey: "7176384017",
    appKey: "9909756346",
    //secretKey: "d2b0a7a95dcfbf0cac630ba34cb73de8",
    secretKey: "9fd4b70a1892bec00906d5dedf5ebea6",
    adminSignUrl: "serveradmin/serverAdmin/",
    adminServerUrl: "/dev/tm/serveradmin/serverAdmin/",
    rootUrl: "/",
    indexUrl: "/index.html"
  };

  /**
   * 签名配置信息
   * @type {{url: string, signUrl: string}}
   */
  var signConfig = {
    url: "",
    signUrl: ""
  };

  /**
   * 初始化配置
   * @param params
   */
  function configInit(params){
    if($.isPlainObject(params)){
      $.extend(true,configs,params);
    }else{
      $.error("初始化配置参数类型错误！");
    }
  }

  /**
   * 签名初始化配置
   * @param params
   */
  function signInit(params){
    if($.isPlainObject(params)){
      $.extend(true,signConfig,params);
    }else{
      $.error("签名初始化配置参数类型错误！");
    }
  }

  /**
   * sign算法
   * @param signUrl
   * @param params
   * @returns {string}
   */
  function signAlgorithm(signUrl,params,md5){
    var sortString = params.sort(), mosaicParam = "";
    for(var i = 0;i<sortString.length;i++){
      mosaicParam += sortString[i] +"_";
    }
    mosaicParam = mosaicParam.substring(0, mosaicParam.length-1);
    var urlParam = signUrl + "_" + mosaicParam+"_" + configs.secretKey;
    var encodeUrlParam = encodeURIComponent(urlParam);
    return md5.createHash(encodeUrlParam);
  }

  /**
   * 获取签名后的URL
   * func：方法名
   * params：请求参数 []
   */
  function getSignUrl(func,params,md5){
    if(!func){
      $.error("获取URL的方法名不能为空！");
    }
    var dateVar = (new Date()).getTime();
    var _signUrl = signConfig.signUrl + func;
    var param = ["appkey=" + configs.appKey,"token=" + configs.token,"dateVar=" + dateVar];
    if($.isArray(params)){
      param = $.merge(param, params);
    }else{
      $.error("获取URL的参数类型错误！");
    }
    var _sign = signAlgorithm(_signUrl,param,md5);
    var _url = signConfig.url + func + "?token=" + configs.token + "&appkey=" + configs.appKey
      +"&sign="+_sign+"&dateVar="+dateVar;
    return _url;
  }

}(jQuery);
